package 剑指offer;


import org.junit.Test;

public class _67把字符串转换成整数 {
	@Test
	public void test() {
		System.out.println(strToInt("42"));
	}
    public int strToInt(String str) {
		int index = 0,length = str.length(),sign=1;
		int max = Integer.MAX_VALUE/10;
		int res = 0;
		if(length == 0) return 0;
		while (str.charAt(index)==' ') if (++index == length) return 0;
		if (str.charAt(index) == '-') sign = -1;
		if (str.charAt(index) == '-'||str.charAt(index) == '+') index++;
		for (int j = index;j<length;j++){
			if (str.charAt(j) < '0'||str.charAt(j) > '9') break;
			if(res > max || res==max && str.charAt(j)>'7')
				return sign == -1 ? Integer.MIN_VALUE :Integer.MAX_VALUE;
			res = res*10+(str.charAt(j)-'0');
		}
		return  sign*res;
	}
}
